package com.grad.webstudy.service.impl;

import com.grad.webstudy.context.UserContext;
import com.grad.webstudy.dao.MessageDao;
import com.grad.webstudy.model.Message;
import com.grad.webstudy.model.User;
import com.grad.webstudy.service.MessageService;
import com.grad.webstudy.service.UserService;
import com.grad.webstudy.vo.MessageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Author: zjf
 * @Date: 2020/1/28 9:52.
 */
@Service
@Transactional
public class MessageServiceImpl implements MessageService {


    @Autowired
    private MessageDao messageDao;


    @Autowired
    private UserService userService;

    @Override
    public boolean recordHistoryMessage(String message, Integer receiveId) {

        User loginUser= UserContext.getLoginUser();
        Message record=new Message();
        record.setMessage(message);
        record.setReceiveId(receiveId);
        record.setSendId(loginUser.getId());
        record.setTime(new Date());

        return messageDao.insert(record)>0;
    }

    @Override
    public List<MessageVo> queryHistoryMessages(Integer receiveId) {

        User loginUser=UserContext.getLoginUser();
        List<Message> messages=messageDao.queryHistoryMessages(loginUser.getId(),receiveId);

        List<MessageVo> messageVos=new ArrayList<>();
        MessageVo messageVo=new MessageVo();
        messageVo.setSendId(loginUser.getId());
        messageVo.setSendUserName(loginUser.getUsername());
        messageVo.setsHeadImagePath(loginUser.getImagePath());

        User receiveUser=userService.selectUserForSystem(receiveId);
        messageVo.setReceiveUserName(receiveUser.getUsername());
        messageVo.setReceiveId(receiveId);
        messageVo.setrHeadImagePath(receiveUser.getImagePath());
        for (Message message : messages) {
            messageVo.setMessage(message.getMessage());
            messageVo.setTime(message.getTime());
            messageVos.add(messageVo);
        }

        return messageVos;
    }



}
